/**
 * Created by easy on 15/5/11.
 */
$(document).ready(function () {
    //初始化pullToRefresh
    pullToRefresh.init({
        loadingFunction: util.pullToRefresh
    });
    var setName = function (name) {
        return name.split(".")[0]
    };
    var getAjaxID = function (string) {
        return string.split("#")[1]
    };
    var getAjaxStatus = function (string) {
        if (string != undefined) {
            return string.split("#")[0]
        } else {
            return "";
        }

    };
    //初始化ractive
    vars.ractiveAbnormalsList = new Ractive({
        el: "CONTAINER-abnormal",
        template: "#TEMPLATE-abnormal",
        data: {
            ractiveData: [], formatDate: function (time, format) {
                return mc.dealTime(parseInt(time), format);
            }, getAjaxID: getAjaxID, getAjaxStatus: getAjaxStatus, setName: setName

        }
    });

});
(function () {
    vars.currentPage = 1;
    vars.pageSize = 10;
    var firstLoad = true;
    basic.deviceReady = function () {
        /*mc.getMessageCount("abnormal", "22");
         mc.getMessageCount("remark", "78");*/
        util.getAbnormals(function () {
            mc.showContent();
            util.syncAbnormalsData(function () {
                util.getAbnormals(function () {
                })
            });
            service.getAbnormalRemarkUnreadCount(function (data) {

            });
        });
        mc.saveDataToLocalStorage("dynamicItem", 1, function () {

        }, "app");
        //mc.showContent();
    };
    /*document.addEventListener('ViewDidAppear', basic.ViewDidAppear, false);

    basic.ViewDidAppear = function () {
        *//*util.getAbnormals(function () {
            mc.showContent();
            util.syncAbnormalsData(function () {
                util.getAbnormals(function () {
                })
            });
            service.getAbnormalRemarkUnreadCount(function (data) {

            });
        });*//*
    };*/
    function refreshListAndHoldingPosition(){
        var refreshListAndHoldingPositionCallback = function(data){
            for (var i in data) {
                data[i].orderAttachment = data[i].orderAttachment != undefined && data[i].orderAttachment != null && data[i].orderAttachment != "undefined" && data[i].orderAttachment != "null" ? JSON.parse(data[i].orderAttachment)[0] : null;
            }
            //alert(JSON.stringify(data))
            vars.ractiveAbnormalsList.data.ractiveData = data;
            vars.ractiveAbnormalsList.update("ractiveData");
            common.showFirstOrderPhotos(data);
            var optionsForMorePage = {
                mode: "normal",
                dataLength: data.length,
                scrollContainer: $("#content"),
                currentPage: vars.currentPage,
                pageSize: (vars.currentPage-1)*vars.pageSize,
                callback: util.paginationOfAbnormalsList
            };
            common.morePage(optionsForMorePage);
        };
        var options={
            pageSize:(vars.currentPage-1)*vars.pageSize,
            currentPage: 1
        };
        //调用审批列表接口获取数据
        service.getAbnormalsData(options,refreshListAndHoldingPositionCallback);
    }
    var viewDidAppearCallback = function(){
        if(firstLoad === false){
            refreshListAndHoldingPosition();
        }
        mc.saveDataToLocalStorage("dynamicItem", 1, function () {

        }, "app");
    };
    document.addEventListener("ViewDidAppear",viewDidAppearCallback,false);
    var viewDidDisappearCallback = function(){
        firstLoad = false;
    };
    document.addEventListener("ViewDidDisappear",viewDidDisappearCallback,false);

    //下拉刷新（同步数据后 显示列表）
    util.pullToRefresh = function () {
        util.syncAbnormalsData(function () {
            util.getAbnormals(pullToRefresh.reset);
        });
    };
    util.jumpToDetail = function (jsonPK, localPK) {
        mc.jump('abnormal-detail.html?keyID=' + jsonPK + '&localPK=' + localPK,'异常详情');
    };
    util.getAbnormals = function (callback) {
        var getAbnormalCallBack = function (data) {
            for (var i in data) {
                data[i].orderAttachment = data[i].orderAttachment != undefined && data[i].orderAttachment != null && data[i].orderAttachment != "undefined" && data[i].orderAttachment != "null" ? JSON.parse(data[i].orderAttachment)[0] : null;
            }
            //alert(JSON.stringify(data))
            vars.ractiveAbnormalsList.data.ractiveData = data;
            vars.ractiveAbnormalsList.update("ractiveData");
            common.showFirstOrderPhotos(data);
            var optionsForMorePage = {
                mode: "normal",
                dataLength: data.length,
                scrollContainer: $("#content"),
                callback: util.paginationOfAbnormalsList
            };
            common.morePage(optionsForMorePage);
            if (callback != undefined) {
                callback();
            }
        };
        var optionsForInitScrollList = {
            mode: "normal",
            scrollContainer: $("#content")
        };
        common.initScrollList(optionsForInitScrollList);
        var options = {
            currentPage: vars.currentPage,
            pageSize: vars.pageSize
        };
        service.getAbnormalsData(options, getAbnormalCallBack);
    };

    // 同步数据。
    util.syncAbnormalsData = function (callback) {
        mc.syncData(["QC_ABNORMAL", "QC_ORDER", "QC_REMARK", "QC_PROCESS"], callback);
    };

    util.showOrderPhotoByIndex = function (key) {
        //alert(key)
        common.showOrderPhotoByIndex(key, 1);
    };

    //获取异常订单列表分页
    util.paginationOfAbnormalsList = function () {
        var paginationOfAbnormalsListCallback = function (data) {
            //alert(JSON.stringify(data) + "-------------")
            for (var i in data) {
                data[i].orderAttachment = data[i].orderAttachment != undefined && data[i].orderAttachment != null && data[i].orderAttachment != "undefined" && data[i].orderAttachment != "null" ? JSON.parse(data[i].orderAttachment)[0] : null;
            }
            vars.ractiveAbnormalsList.data.ractiveData = $.merge(vars.ractiveAbnormalsList.data.ractiveData, data);
            vars.ractiveAbnormalsList.update("ractiveData");
            common.showFirstOrderPhotos(data, vars.currentPage);
            var optionsForMorePage = {
                mode: "normal",
                dataLength: data.length,
                scrollContainer: $("#content"),
                callback: util.paginationOfAbnormalsList
            };
            common.morePage(optionsForMorePage);
        };
        var options = {
            currentPage: vars.currentPage,
            pageSize: vars.pageSize
        };
        service.getAbnormalsData(options, paginationOfAbnormalsListCallback)
    };

    // 提交开始时通知页面
    util.ajaxStarted = function (ajaxID, matchIDs) {
        var id = "abnormalCreate" + ajaxID;
        var obj = document.getElementById(id)
        if (obj) {
            var ajaxItem = $("#abnormalCreate" + ajaxID);
            common.changeAjaxBadgeStatus(1, ajaxItem, "abnormal", ajaxID);
        } else {
            util.changeAbnormalStatus(matchIDs);
        }
    };

    // 提交完成后通知页面
    util.ajaxCompleted = function (ajaxID, result, matchIDs) {
        var id = "abnormalCreate" + ajaxID;
        var obj = document.getElementById(id);
        if (obj) {
            var ajaxItem = $("#abnormalCreate" + ajaxID);
            if (result == "success") {
                common.changeAjaxBadgeStatus(2, ajaxItem, "abnormal", ajaxID, util.getAbnormalDetail);
            } else if (result == "failed") {
                common.changeAjaxBadgeStatus(3, ajaxItem, "abnormal", ajaxID);
            }
        } else {
            util.changeAbnormalStatus(matchIDs);
        }
    };

    // 根据提交的不同阶段改变页面的状态
    util.changeAbnormalStatus = function (matchIDs) {
        var matchIDsArr = matchIDs.split(",");
        for (var i = 0; i < matchIDsArr.length; i++) {
            var execFindStatus = function () {
                var abnormalID = matchIDsArr[i];
                var abnormalItem = $(document.getElementById(abnormalID));
                if (abnormalItem != undefined) {
                    var findAbnormalStatusCallback = function (data) {
                        //alert(JSON.stringify(data))
                        var descriptionStatus = data[0].descriptionStatus ? data[0].descriptionStatus.split("#")[0] : "";
                        var abnormalStatusStatus = data[0].abnormalStatusStatus ? data[0].abnormalStatusStatus.split("#")[0] : "";
                        var remarkStatus = data[0].remarkStatus ? data[0].remarkStatus.split("#")[0] : "";
                        var attachmentStatus = data[0].attachmentStatus ? data[0].attachmentStatus.split("#")[0] : "";
                        if (descriptionStatus == "uploading" || abnormalStatusStatus == "uploading" || remarkStatus == "uploading" || attachmentStatus == "uploading") {
                            common.changeAjaxBadgeStatus(1, abnormalItem, 'abnormal', abnormalID)
                        } else {
                            if (descriptionStatus == "failed" || abnormalStatusStatus == "failed" || remarkStatus == "failed" || attachmentStatus == "failed") {
                                common.changeAjaxBadgeStatus(3, abnormalItem, 'abnormal', abnormalID)
                            } else {
                                common.changeAjaxBadgeStatus(2, abnormalItem, 'abnormal', abnormalID, util.getAbnormalDetail)
                            }
                        }
                    };
                    var SQLOfFindOrderStatus = "SELECT descriptionStatus,abnormalStatusStatus,remarkStatus FROM QC_ABNORMAL WHERE jsonPK = ?;";
                    mc.execSQL(SQLOfFindOrderStatus, [abnormalID], findAbnormalStatusCallback);
                }
            };
            execFindStatus();
        }
    };

    // 重新上传
    util.findThisAbnormalsFailedTask = function (touchObj, abnormalID) {
        var sql = "SELECT FCloudDataTransferID FROM T_CloudDataTransferCenter WHERE FCloudDataTransferMatchIDs LIKE '%" + abnormalID + "%' AND FCloudDataTransferState = 'failed'";
        var findThisAbnormalsFailedTaskCallback = function (data) {
            for (var i = 0; i < data.length; i++) {
                data[i] = data[i].FCloudDataTransferID.toString();
            }
            common.execUploadAjaxTask(touchObj, data);
        };
        mc.execSQL(sql, [], findThisAbnormalsFailedTaskCallback);
    };

    // 第一次装APP时 将所有状态为上传中的数据改为失败 并统计
    util.appInit = function () {
        var resetOrderStatus1 = "UPDATE QC_ORDER SET processStatus = 'failed' || substr(processStatus,10,length(processStatus)-9) where processStatus like 'uploading%';";
        var resetOrderStatus2 = "UPDATE QC_ORDER SET abnormalStatus = 'failed' || substr(abnormalStatus,10,length(abnormalStatus)-9) where abnormalStatus like 'uploading%';";
        var resetOrderStatus3 = "UPDATE QC_ORDER SET remarkStatus = 'failed' || substr(remarkStatus,10,length(remarkStatus)-9) where remarkStatus like 'uploading%';";
        var resetProcessStatus1 = "UPDATE QC_PROCESS SET abnormalStatus = 'failed' || substr(abnormalStatus,10,length(abnormalStatus)-9) where abnormalStatus like 'uploading%';";
        var resetProcessStatus2 = "UPDATE QC_PROCESS SET remarkStatus = 'failed' || substr(remarkStatus,10,length(remarkStatus)-9) where remarkStatus like 'uploading%';";
        var resetProcessStatus3 = "UPDATE QC_PROCESS SET completeQuantityStatus = 'failed' || substr(completeQuantityStatus,10,length(completeQuantityStatus)-9) where completeQuantityStatus like 'uploading%';";
        var resetProcessStatus4 = "UPDATE QC_PROCESS SET actualTimeStatus = 'failed' || substr(actualTimeStatus,10,length(actualTimeStatus)-9) where actualTimeStatus like 'uploading%';";
        var resetProcessStatus5 = "UPDATE QC_PROCESS SET estimatedTimeStatus = 'failed' || substr(estimatedTimeStatus,10,length(estimatedTimeStatus)-9) where estimatedTimeStatus like 'uploading%';";
        var resetRemarkStatus1 = "UPDATE QC_REMARK SET remarkStatus = 'failed' || substr(remarkStatus,10,length(remarkStatus)-9) where remarkStatus like 'uploading%';";
        var resetRemarkStatus2 = "UPDATE QC_REMARK SET attachmentStatus = 'failed' || substr(attachmentStatus,10,length(attachmentStatus)-9) where attachmentStatus like 'uploading%';";
        var resetRemarkStatus3 = "UPDATE QC_REMARK SET completeQuantityStatus = 'failed' || substr(completeQuantityStatus,10,length(completeQuantityStatus)-9) where completeQuantityStatus like 'uploading%';";
        var resetRemarkStatus4 = "UPDATE QC_REMARK SET descriptionStatus = 'failed' || substr(descriptionStatus,10,length(descriptionStatus)-9) where descriptionStatus like 'uploading%';";
        var resetRemarkStatus5 = "UPDATE QC_REMARK SET createStatus = 'failed' || substr(createStatus,10,length(createStatus)-9) where createStatus like 'uploading%';";
        var resetAbnormalStatus1 = "UPDATE QC_ABNORMAL SET abnormalStatusStatus = 'failed' || substr(abnormalStatusStatus,10,length(abnormalStatusStatus)-9) where abnormalStatusStatus like 'uploading%';";
        var resetAbnormalStatus2 = "UPDATE QC_ABNORMAL SET remarkStatus = 'failed' || substr(remarkStatus,10,length(remarkStatus)-9) where remarkStatus like 'uploading%';";
        var resetAbnormalStatus3 = "UPDATE QC_ABNORMAL SET createStatus = 'failed' || substr(createStatus,10,length(createStatus)-9) where createStatus like 'uploading%';";
        var resetAbnormalStatus4 = "UPDATE QC_ABNORMAL SET descriptionStatus = 'failed' || substr(descriptionStatus,10,length(descriptionStatus)-9) where descriptionStatus like 'uploading%';";
        var resetAbnormalStatus5 = "UPDATE QC_ABNORMAL SET attachmentStatus = 'failed' || substr(attachmentStatus,10,length(attachmentStatus)-9) where attachmentStatus like 'uploading%';";
        var sqlArr = [resetOrderStatus1, resetOrderStatus2, resetOrderStatus3, resetProcessStatus1, resetProcessStatus2, resetProcessStatus3, resetProcessStatus4, resetProcessStatus5, resetRemarkStatus1, resetRemarkStatus2, resetRemarkStatus3, resetRemarkStatus4, resetRemarkStatus5, resetAbnormalStatus1, resetAbnormalStatus2, resetAbnormalStatus3, resetAbnormalStatus4, resetAbnormalStatus5];
        var execSQLItem = function (index) {
            mc.execSQL(sqlArr[index],[], function (data) {
                if(index == sqlArr.length - 1) {
                    mc.killLaunch();
                }
            });
        };
        for(var i in sqlArr) {
            execSQLItem(i);
        }
        service.getProcessUnreadCount(function (dataCount) {
            if(dataCount.count>0) {
                $("#dynamicCount").text(dataCount.count).show(0);
                mc.getMessageCount("remark", ' ');
            }else{
                mc.getMessageCount("remark", '');
            }
        });
    }

})();